package com.ramos.kuaixiao.network;

import android.os.AsyncTask;
import android.os.Looper;
import android.util.Log;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.SyncHttpClient;
import com.ramos.kuaixiao.App;
import com.ramos.kuaixiao.db.CustomerDB;
import com.ramos.kuaixiao.db.SaleCustomerDB;
import com.ramos.kuaixiao.entity.Customer;
import com.ramos.kuaixiao.entity.SaleCustomer;
import com.ramos.kuaixiao.utils.CommUtil;
import com.ramos.kuaixiao.utils.FileUtil;
import com.ramos.kuaixiao.utils.NetUtils;
import com.ramos.kuaixiao.utils.SharedPreference;
import com.ramos.kuaixiao.utils.ToastUtils;
import com.ramos.kuaixiao.utils.Utils;

import org.apache.http.Header;

import java.io.File;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Scanner;
import java.util.Set;

public class DownloadCustomerTask extends AsyncTask<Void, Integer, Boolean> {
    private final static String TAG = "DownloadCustomerTask";
    private Set<String> customers = new HashSet<>();

    @Override
    protected void onPreExecute() {

    }

    @Override
    protected Boolean doInBackground(Void... params) {
        try {
            //获取所有商店数据
            //getAllCustomer();
            getAllLocalSaleCustomer();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return true;
    }

    private void getAllLocalCustomer(Set<String> customers) {
        List<Customer> tmplist = new ArrayList<>();
        File file = new File(FileUtil.getDataPath(App.mContext) + "/tbl_customer.csv");
        List<Customer> list = readCustomerCsv(file.getAbsolutePath());
        CommUtil.d(App.mContext,TAG, "tbl_Customer:" + list.size());
        CommUtil.d(App.mContext,TAG, "tbl_customers:" + customers.size());
        if (customers != null && customers.size() > 0) {
            for (Customer customer : list) {
                for (String s : customers) {
                    if (customer.getId().equals(s)) {
                        tmplist.add(customer);
                    }
                }
            }
            CommUtil.d(App.mContext,TAG, "tbl_Customer1:" + tmplist.size());
            CustomerDB customerDB1 = new CustomerDB();
            customerDB1.addAllCustomer(tmplist);
            Looper.prepare();
            ToastUtils.show("客户数据已加载完成，总共"+tmplist.size()+"条数据");
            Looper.loop();

        } else {
            Looper.prepare();
            ToastUtils.show("未发现客户数据！");
            Looper.loop();
        }
    }

    private void getAllLocalSaleCustomer() {
        File file = new File(FileUtil.getDataPath(App.mContext) + "/tbl_sale_customer.csv");
        List<SaleCustomer> list = readSaleCustomerCsv(file.getAbsolutePath());
        CommUtil.d(App.mContext,TAG, "tbl_SaleCustomer:" + list.size());
        SaleCustomerDB customerDB = new SaleCustomerDB();
        customerDB.addAllCustomer(list);
        for (SaleCustomer sale : list) {
            if (sale.getSaleId().equals(SharedPreference.getPreferString("id"))) {
                customers.add(sale.getCustomerId());
            }
        }
        getAllLocalCustomer(customers);
    }

    private List<SaleCustomer> readSaleCustomerCsv(String absolutePath) {
        List<SaleCustomer> readerArr = new ArrayList<>();
        Scanner in = Utils.readCsv(absolutePath);
        try {
            in.nextLine();
            while (in.hasNextLine()) {
                String s = in.nextLine();
                String[] lines = s.split(",");
                if (Utils.replaceStr(lines[20]).equals("F")) {
                    SaleCustomer bean = new SaleCustomer(Utils.replaceStr(lines[4]), Utils.replaceStr(lines[3]), Utils.replaceStr(lines[1])
                            , Utils.replaceStr(lines[1]), Long.valueOf(Utils.replaceStr(lines[1])));
                    readerArr.add(bean);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return readerArr;
    }

    public List<Customer> readCustomerCsv(String path) {
        List<Customer> readerArr = new ArrayList<>();
        Scanner in = Utils.readCsv(path);
        try {
            in.nextLine();
            while (in.hasNextLine()) {
                String s = in.nextLine();
                String[] lines = s.split(",");
                /*if (Utils.replaceStr(lines[2]).equals(SharedPreference.getPreferString("dealer"))) {*/
                    Customer bean = new Customer(Utils.replaceStr(lines[0]), Utils.replaceStr(lines[1]), Utils.replaceStr(lines[3]), "",
                            Utils.replaceStr(lines[27]), Utils.replaceStr(lines[22]), Utils.replaceStr(lines[19]), Utils.replaceStr(lines[6]),Utils.replaceStr(lines[30]));
                    readerArr.add(bean);
                /*}*/
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return readerArr;
    }

    @Override
    protected void onProgressUpdate(Integer... values) {

    }

    @Override
    protected void onPostExecute(Boolean result) {

    }

    private void getAllCustomer() {
        try {
            /*String url = NetUtils.CUSTOMER_ALL_LOCAL;
            String path = url + SharedPreference.getPreferString("dealer");
            Log.d(TAG, "CUSTOMER_ALL_LOCAL:path=" + path);*/

            String url = NetUtils.CUSTOMER_ALL_WITH_USER;
            org.json.JSONObject object = new org.json.JSONObject();
            object.put("dealer", SharedPreference.getPreferString("dealer"));
            object.put("sale", SharedPreference.getPreferString("id"));
            Log.d(TAG, "CUSTOMER_ALL_LOCAL:path=" + object.toString());
            String encode = URLEncoder.encode(object.toString(), "UTF-8");
            String path = url + encode;
            Log.d(TAG, "CUSTOMER_ALL_LOCAL:path=" + path);

            SyncHttpClient client = new SyncHttpClient(); // 创建异步请求的客户端对象
            // 创建请求参数的封装的对象
            client.setTimeout(120000);
            client.get(path, new AsyncHttpResponseHandler() {

                @Override
                public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                    //statusCode:状态码    headers：头信息  responseBody：返回的内容，返回的实体
                    //判断状态码
                    try {
                        String result = new String(responseBody, "utf-8");
                        JSONObject jsonObejct = JSONObject.parseObject(result);
                        Log.d(TAG, "CUSTOMER_ALL_LOCAL:result=" + result);
                        if (jsonObejct.getInteger("status") == 200) {
                            //JSONObject data = jsonObejct.getJSONObject("data");
                            List<Customer> customerList = JSONArray.parseArray(jsonObejct.getJSONArray("data").toString(), Customer.class);
                            if (customerList != null && customerList.size() > 0) {
                                Log.d(TAG, "CUSTOMER_ALL_LOCAL:mCustomerList=" + customerList.size());
                                CustomerDB customerDB = new CustomerDB();
                                customerDB.addAllCustomer(customerList);
                            }
                        }
                    } catch (Exception e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }

                @Override
                public void onFailure(int statusCode, Header[] headers,
                                      byte[] responseBody, Throwable error) {
                    error.printStackTrace();
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
